<template>
  <div class="CostInfo">
    <div class="CostInfo-header">
      <div style="font-size: 16px; font-weight: 400; color: #242633">费用明细</div>
    </div>
    <div class="CostInfo-container">
      <div :key="idx" class="containerItem">
        <div class="containerItem-Table">
          <a-table
            :columns="columns"
            :data-source="CostInfoList"
            rowKey="id"
            :loading="tableLoading"
            :pagination="false"
            :scroll="{ y: 400 }"
            :expandedRowKeys="pageOpen ? expandedRowKeys : false"
          >
            <!-- 序号 -->
            <template #index="{ index }">
              <span>
                {{ ++index }}
              </span>
            </template>
            <!-- 确认日期 -->
            <template #confirmDate="{ record }">
              <a-date-picker
                v-if="(!record.id || record.hasCashAmount === 0) && pageType !== 'view'"
                v-model:value="record.confirmDate"
                :getCalendarContainer="getCalendarContainer"
                suffix-icon=" "
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                @change="recordChange(record)"
              />
              <span v-else>{{ record.confirmDate }}</span>
            </template>
            <!-- 客户确认金额 -->
            <template #confirmAmount="{ record }">
              <a-input-number
                v-if="(!record.id || record.hasCashAmount === 0) && pageType !== 'view'"
                v-model:value="record.confirmAmount"
                style="width: 108px; text-align: right"
                @change="recordChange(record)"
              />
              <span v-else>{{ record.confirmAmount }}</span>
            </template>
            <!-- 结算单号 -->
            <template #settlementNo="{ record }">
              <a-input
                v-if="pageType !== 'view'"
                v-model:value="record.settlementNo"
                maxlength="30"
                @change="recordChange(record)"
              />
              <span v-else>{{ record.confirmAmount }}</span>
            </template>
            <!-- 已兑付金额 -->
            <template #hasCashAmount="{ record }">
              <span>{{ record.hasCashAmount }}</span>
            </template>
            <!-- 待兑付金额 -->
            <template #waitCashAmount="{ record }">
              <span>{{ record.waitCashAmount }}</span>
            </template>
            <template v-if="pageType !== 'view'" #cash="{ record, index }">
              <div v-if="record.editing">
                <a-button type="link" size="small" @click="SaveList(record)">保存</a-button>
                <a-button type="link" size="small" @click="cancelItem(record, index)"
                  >取消</a-button
                >
              </div>
              <div v-else>
                <a-button
                  v-if="!record.editing && record.id"
                  :disabled="!record.waitCashAmount"
                  type="link"
                  size="small"
                  @click="DialogCash(record)"
                  >兑付</a-button
                >
                <a-button
                  v-if="(!record.waitCashAmount && record.id) || record.hasCashAmount > 0"
                  type="link"
                  size="small"
                  style="margin-left: 8px"
                  disabled
                  >删除</a-button
                >
                <a-popconfirm
                  v-if="record.waitCashAmount && !record.editing && record.hasCashAmount === 0"
                  title="确定删除这条明细?"
                  @confirm.stop="delCash(record, index)"
                >
                  <a-button
                    v-if="record.waitCashAmount && !record.editing"
                    type="link"
                    size="small"
                    style="margin-left: 8px"
                    >删除</a-button
                  >
                </a-popconfirm>
              </div>
            </template>
            <!--  合计 -->
            <!-- <div class="tableTwo"> -->
            <template #footer>
              <a-table
                class="footerTable"
                rowKey="id"
                :columns="footerColumns"
                :dataSource="footerData"
                :pagination="false"
              >
                <template #sumTitle>合计</template>
              </a-table>
            </template>
            <template #expandedRowRender="{ record }">
              <a-table
                :columns="innerColumns"
                :data-source="record.detailCashVOList"
                rowKey="id"
                :pagination="false"
              >
                <template #indexs="{ index }">
                  <span>
                    {{ ++index }}
                  </span>
                </template>
                <!-- 兑付日期 -->
                <template #cashTime="cashTimeTest">
                  <a-date-picker
                    v-if="record.waitCashAmount && pageType !== 'view'"
                    v-model:value="cashTimeTest.record.cashTime"
                    suffix-icon=" "
                    style="width: 128px"
                    :getCalendarContainer="getCalendarContainer"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    @change="recordChange(cashTimeTest.record)"
                  />
                  <span v-else>{{ cashTimeTest.record.cashTime }}</span>
                </template>
                <!-- 兑付金额 -->
                <template #cashAmount="cashMonTest">
                  <a-input-number
                    v-if="record.waitCashAmount && pageType !== 'view'"
                    v-model:value="cashMonTest.record.cashAmount"
                    style="width: 108px"
                    @change="recordChange(cashMonTest.record)"
                  />
                  <span v-else>{{ cashMonTest.record.cashAmount }}</span>
                </template>
                <template v-if="pageType !== 'view'" #action="action">
                  <a-button
                    v-if="action.record.editing"
                    type="link"
                    size="small"
                    @click="saveCash(action.record)"
                    >保存</a-button
                  >
                  <a-button
                    v-if="action.record.editing"
                    type="link"
                    size="small"
                    @click="cancelItem(action.record)"
                    >取消</a-button
                  >
                  <a-popconfirm
                    v-if="!action.record.editing"
                    title="确定删除这条明细?"
                    @confirm.stop="delItem(action.record, action.index, record.detailCashVOList)"
                  >
                    <a-button type="link" size="small">删除</a-button>
                  </a-popconfirm>
                </template>
              </a-table>
            </template>
          </a-table>
        </div>

        <div v-if="pageType !== 'view'" class="AddBtn" @click="addRow('new')">
          <i class="addLine"></i>新增行</div
        >
        <div class="pagination">
          <a-pagination
            size="small"
            :total="pagination.total"
            :current="pagination.current"
            :pageSize="pagination.pagesize"
            :pageSizeOptions="pagination.pageSizeOptions"
            show-size-changer
            show-quick-jumper
            @change="pageIndexChange"
            @showSizeChange="pageSizeChange"
          />
        </div>
        <!-- 兑付弹窗 -->
        <cash-dialog
          v-model:dialogCash="dialogCash"
          :confirmCosh="confirmCosh"
          @addDepts="getList('save', confirmCosh)"
        ></cash-dialog>
      </div>
    </div>
  </div>
</template>
<script>
  import { defineComponent, watch, onMounted, reactive, toRefs } from 'vue'
  import { useRoute } from 'vue-router'
  import { message } from 'ant-design-vue'
  import { CostInfoList, columns, footerColumns } from './data'
  import CashDialog from './CashDialog.vue'
  import api from '@/api'
  export default defineComponent({
    name: 'CostInfo',
    components: {
      CashDialog
    },
    props: {
      expenseOrderNo: {
        type: String,
        defalt: ''
      }
    },
    setup(props) {
      const route = useRoute()
      const state = reactive({
        expandedRowKeys: [], // 子嵌套展开id
        pageType: 'edit',
        pageOpen: false,
        costInfoForm: [{ customerCode: '', customerName: '' }],
        columns: columns,
        footerColumns: footerColumns,
        tableLoading: false,
        CostInfoList: [],
        expenseOrderNo: '',
        isShowShop: false,
        checkedList: [],
        dialogCash: false, // 兑付框
        confirmCosh: null,
        showSelectCustom: false,
        showSelectStore: false,
        selectCustomerIdx: null,
        selectStoreIdx: null,
        pagination: {
          current: 1,
          pagesize: 10,
          pageSizeOptions: ['10', '50', '100', '200'],
          showSizeChanger: true,
          showQuickJumper: true,
          total: 10,
          showTotal: (total) => `共${total}条`
        },
        // 合计数据
        footerData: [
          {
            index: '合计',
            confirmAmount: 0,
            hasCashAmount: 0,
            waitCashAmount: 0
          }
        ],
        // 兑付明细二级列表
        innerColumns: [
          {
            title: '序号',
            dataIndex: 'number',
            width: 200,
            key: 'number',
            slots: { customRender: 'indexs' }
            // customRender: (index) => `${index + 1}`
          },
          {
            title: '兑付日期',
            dataIndex: 'cashTime',
            key: 'cashTimes',
            slots: { customRender: 'cashTime' }
          },
          {
            title: '兑付金额',
            dataIndex: 'cashAmount',
            key: 'cashAmount',
            slots: { customRender: 'cashAmount' }
          },
          {
            title: '操作',
            key: 'operation',
            width: 150,
            slots: { customRender: 'action' }
          }
        ],
        // 兑付明细二级数据
        innerData: []
      })
      const binFn = {
        // 新增某个客户下的一行
        addRow(type) {
          let obj = {
            editing: true,
            confirmDate: '', // 确认时间
            confirmAmount: '', // 确认金额
            hasCashAmount: 0, // 已兑付金额
            waitCashAmount: 0, // 待兑付金额
            type: type
          }
          state.CostInfoList.unshift(obj)
        },
        getCalendarContainer(e) {
          return document.body
        },
        recordChange(record) {
          record.editing = true
        },
        // 分页事件
        pageIndexChange(page) {
          state.pagination.current = page
          binFn.getList('refresh')
        },
        // 页码事件
        pageSizeChange(current, size) {
          state.pagination.current = 1
          state.pagination.pagesize = size
          binFn.getList('refresh')
        },
        // 删除某个客户下的一行
        async delCash(record, index) {
          console.log(index, 'index')
          let res = ''
          state.tableLoading = true
          res = await api.businessDiscountDetail.deleteConfim(record.id).catch(() => {
            state.tableLoading = false
            res = false
          })
          if (res) {
            message.success(res)
            state.CostInfoList.splice(index, 1)
            binFn.getList()
          }
        },
        // 兑付保存
        async saveCash(record) {
          let res = true
          state.tableLoading = true
          let cashid = record.id
          record.cashAmount = parseFloat(record.cashAmount)
          if (!record.cashAmount) {
            message.error('客户确认金额必须大于零')
            return false
          }
          if (!record.cashTime) {
            message.error('确认日期不能为空')
            return false
          }
          await api.businessDiscountDetail
            .cashUpdata(cashid, {
              directDetailId: record.directDetailId,
              cashAmount: record.cashAmount,
              cashTime: record.cashTime
            })
            .catch(() => {
              state.tableLoading = false
              res = false
            })
          if (res) {
            message.success('保存成功')
            record.editing = false
            binFn.getList()
          }
        },
        // 兑付删除
        async delItem(record, index, list) {
          state.tableLoading = true
          let cashid = record.id
          let res = ''
          res = await api.businessDiscountDetail.cashDelete(cashid).catch(() => {
            state.tableLoading = false
            res = false
          })
          if (res) {
            message.success(res)
            list.splice(index, 1)
            binFn.getList()
          }
        },
        // 取消
        cancelItem(record, index) {
          console.log(record, 'record')
          record.editing = false
          if (record.id) {
            // 接口数据删除
            if (record.waitCashAmount) {
              // 上级
              record.confirmAmount = record.waitCashAmount
              record.confirmDate = record.retainConfirmDate
              record.settlementNo = record.retainSettlementNo
            } else {
              // 子集
              record.cashAmount = record.retainCashAmount
            }
          } else {
            // 新增行删除
            state.CostInfoList.splice(index, 1)
          }
        },
        // 列表数据
        async getList(type, record) {
          state.tableLoading = true
          const res = await api.businessDiscountDetail
            .costInfo(state.expenseOrderNo, {
              pageSize: state.pagination.pagesize,
              pageNum: state.pagination.current
            })
            .catch(() => {})
          state.tableLoading = false
          if (res) {
            state.footerData = [
              {
                sumTitle: '合计',
                confirmAmount: res.sumHasConfirmAmount,
                hasCashAmount: res.sumHasCashAmount,
                waitCashAmount: res.sumWaitCashAmount
              }
            ]
            state.pagination.total = res.detailList.total
            if (type === 'save') {
              // 保存
              let index = 0
              if (record.id) {
                index = res.detailList.list.findIndex((e) => e.id === record.id)
              } else {
                index = res.detailList.list.findIndex(
                  (e) =>
                    e.confirmDate === record.confirmDate && e.confirmAmount === record.confirmAmount
                )
              }
              const item = res.detailList.list[index]
              record.id = item.id
              record.retainConfirmDate = item.confirmDate
              record.hasCashAmount = item.hasCashAmount
              record.waitCashAmount = item.waitCashAmount
              record.retainSettlementNo = item.settlementNo
              record.detailCashVOList = item.detailCashVOList.filter((cItem) => {
                cItem.editing = false
                cItem.retainCashAmount = cItem.cashAmount
                return cItem
              })
            } else if (type === 'refresh') {
              // 刷新列表
              state.CostInfoList = res.detailList.list.filter((item) => {
                item.editing = false
                item.retainConfirmDate = item.confirmDate
                item.retainSettlementNo = item.settlementNo
                item.detailCashVOList = item.detailCashVOList.filter((cItem) => {
                  cItem.editing = false
                  cItem.retainCashAmount = cItem.cashAmount
                  return cItem
                })
                return item
              })
            }
            // 需要展开的子嵌套id
            state.expandedRowKeys = state.CostInfoList.map((item) => item.id)
          }
        },
        // 保存
        async SaveList(record) {
          let res = true
          if (record.confirmAmount === '' || record.confirmAmount === null) {
            message.error('请输入客户确认金额')
            return false
          }
          state.tableLoading = true
          if (record.id) {
            // 修改
            await api.businessDiscountDetail
              .updataList({
                confirmAmount: record.confirmAmount,
                confirmDate: record.confirmDate,
                id: record.id,
                settlementNo: record.settlementNo
              })
              .catch(() => {
                state.tableLoading = false
                res = false
              })
          } else {
            // 新增
            await api.businessDiscountDetail
              .addList({
                confirmAmount: record.confirmAmount,
                confirmDate: record.confirmDate,
                settlementNo: record.settlementNo,
                expenseOrderNo: state.expenseOrderNo
              })
              .catch(() => {
                state.tableLoading = false
                res = false
              })
          }
          if (res) {
            message.success('操作成功')
            record.editing = false
            binFn.getList('save', record)
          }
        },
        // 待兑付弹框
        DialogCash(record) {
          state.confirmCosh = record
          state.confirmCosh.waitConfirmAmount = state.footerData[0].waitCashAmount
          state.dialogCash = true
        }
      }
      watch(
        () => props.expenseOrderNo,
        function (val) {
          state.expenseOrderNo = val
          binFn.getList('refresh')
        }
      )
      onMounted(() => {
        if (route.query.type === 'openExpand') {
          // 查看页，且展开子嵌套
          state.pageType = 'view'
          state.pageOpen = true
        } else {
          state.pageType = route.query.type
        }
        state.CostInfoList = []
        state.CostInfoList = CostInfoList
      })
      return {
        ...toRefs(state),
        ...binFn
      }
    }
  })
</script>
<style lang="less" scoped>
  .CostInfo {
    background-color: #fff;
    padding: 24px;
    margin: 24px;
    &-header {
      display: flex;
      justify-content: space-between;
    }
    &-container {
      .containerItem {
        &-top {
          display: flex;
          justify-content: space-between;
          margin-top: 18px;
          .headerLeft {
            display: flex;
            .labelName {
              display: inline-block;
              width: 100px;
              text-align: right;
            }
          }
        }
        &-Table {
          margin-top: 18px;
          // :deep(.components-table-demo-nested .ant-table-content:first-child) {
          //   // display: none;
          //   // height: 480px;
          //   max-height: 480px;
          // }
          // max-height: 480px;
          // overflow: auto;
          :deep(.childTable .ant-table-content:first-child) {
            // display: none;
            // background-color: yellow;
            height: auto;
          }

          // &:deep(.footerTable .ant-table-thead) {
          //   display: none;
          // }
          // &:deep(.ant-table-footer) {
          //   height: 58px;
          //   padding: 0;
          // }
          &:deep(.ant-table-expanded-row table) {
            background: #fafafa;
            // background-color: yellow !important;
          }
          & :deep(.ant-table) {
            overflow: auto;
          }
          // &:deep(.ant-table-expanded-row table) {
          //   background: #fafafa;
          //   // background-color: yellow !important;
          // }
          // & :deep(.ant-table-footer) {
          //   padding: unset;
          //   background-color: #fff;
          //   padding-left: 98px;
          // }
        }
        .AddBtn {
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          margin-top: 16px;
          text-align: center;
          padding: 6px 0;
          border: 1px dashed #d9d9d9;
        }
        .addLine {
          display: block;
          width: 16px;
          height: 16px;
          margin-right: 12px;
          background: url('@/assets/img/common/newAdd.png') no-repeat center center/100% 100%;
          cursor: pointer;
        }
      }
    }
    :deep(.ant-table-expanded-row table) {
      background: #fafafa;
    }
    :deep(.ant-input-number) {
      border: none;
    }
    :deep(.ant-input-number-handler-wrap) {
      display: none;
    }
    :deep(.ant-input-number-input) {
      font-size: 12px;
      text-align: right;
      padding: 0;
    }
    :deep(.ant-input-number-handler) {
      display: none;
    }
    :deep(.ant-input) {
      line-height: 30px;
      font-size: 12px;
      border: none;
      padding: 0;
    }
    :deep(.ant-calendar-picker-input) {
      text-align: center !important;
    }
    :deep(.ant-table-thead) {
      height: 54px;
    }
    :deep(.ant-table-row) {
      height: 58px;
    }
    &:deep(.footerTable .ant-table-thead) {
      display: none;
    }
    &:deep(.ant-table-footer) {
      padding: 0 !important;
    }
    &:deep(.ant-table-expanded-row table) {
      background: #fafafa;
      // background-color: yellow !important;
    }
    // &:deep(.footerTable .ant-table-row-cell-break-word:first-child) {
    //   padding-left: 70px !important;
    // }
    .pagination {
      text-align: right;
      margin-top: 24px;
    }
  }
</style>
